package com.lcq.demo.common.config;

import com.lcq.demo.common.job.ApiTaskJob;
import com.lcq.demo.common.job.MyJob;
import com.lcq.demo.common.job.ReflectionTaskExecutorJob;
import com.lcq.demo.entity.po.ScheduleTask;
import com.lcq.demo.service.ScheduleTaskService;
import org.quartz.*;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class TaskInitializer implements ApplicationRunner {

    @Resource
    private Scheduler scheduler;

    @Resource
    private ScheduleTaskService scheduleTaskService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<ScheduleTask> executingTasks = scheduleTaskService.getExecutingTasks();
        for (ScheduleTask task : executingTasks) {
            String callTarget = task.getCallTarget();
            JobDetail jobDetail = null;
            if (callTarget.startsWith("com.lcq")) {
                jobDetail = JobBuilder.newJob(ReflectionTaskExecutorJob.class)
                        .withIdentity(task.getTaskName(), "group1")
                        .usingJobData("taskId", task.getId())
                        .usingJobData("taskName", task.getTaskName())
                        .usingJobData("callTarget", task.getCallTarget())
                        .build();
            } else {
                jobDetail = JobBuilder.newJob(ApiTaskJob.class)
                        .withIdentity(task.getTaskName(), "group2")
                        .usingJobData("taskId", task.getId())
                        .usingJobData("taskName", task.getTaskName())
                        .usingJobData("callTarget", task.getCallTarget())
                        .build();
            }


            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCronExpression());
            CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(task.getTaskName(), "group1")
                    .withSchedule(scheduleBuilder)
                    .build();

            scheduler.scheduleJob(jobDetail, cronTrigger);
        }
    }
}
